﻿using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Win32;

using Xc.DataAccess.Core.Extensions;
using Xc.DataAccess.Core.Services;
using Xc.Logics.HyperTerminalCore.Udp.Models;
using Xc.Logics.HyperTerminalCore.Udp.ViewModels;
using Xc.Views.Core;

namespace Xc.Logics.HyperTerminalCore.Udp.Views
{
    /// <summary>
    /// PackageView.xaml 的交互逻辑
    /// </summary>
    public partial class PackageView : UserControl
    {
        private readonly IApplicationBooster<AppSetting> applicationBooster;
        private readonly IConverterService converterService;
        private readonly IServiceProvider serviceProvider;

        private IOptionsSnapshot<AppSetting> options;
        public PackageView(IApplicationBooster<AppSetting> applicationBooster, IConverterService converterService,IServiceProvider serviceProvider)
        {
            InitializeComponent();
            this.applicationBooster = applicationBooster;
            this.converterService = converterService;
            this.serviceProvider = serviceProvider;
            options = serviceProvider.CreateScope().ServiceProvider.GetService<IOptionsSnapshot<AppSetting>>();
        }

        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "原始固件包|*.bin|打包后的固件包|*.pkgbin";
            if (openFileDialog.ShowDialog()==true)
            {
                FileInfo fileInfo=new FileInfo(openFileDialog.FileName);
                switch (fileInfo.Extension)
                {
                    case ".bin": 
                        {
                            var PackageRawDatas=File.ReadAllBytes(openFileDialog.FileName);
                            var length = options.Value.PackageSize;
                            var index = PackageRawDatas.Length / length;
                            var remain= PackageRawDatas.Length % length;
                            if (remain!=0)
                            {
                                index++;
                            }
                            List<PackageInfoItem> items = new List<PackageInfoItem>();
                            int crc = 0;
                            for (int i = 0; i < index; i++)
                            {
                                var item = new PackageInfoItem { PackageIndex = i, PackageData = PackageRawDatas.Skip(length * i).Take(length).ToArray() };
                                crc =  Xc.DataAccess.PcpChannels.Frame.CrcCheck(item.PackageData,crc);
                                item.CRC = (ushort)crc;
                                items.Add(item);
                            }
                            this.ViewModel.PackageInfo = new PackageInfo
                            {
                                PackageCheck = (ushort)crc,
                                PackageSize = length,
                                PackageInfoItems = items.ToArray(),
                                Version ="1.0"
                            };
                        }
                        break;
                    case ".pkgbin": 
                        {
                           var text=  File.ReadAllText(openFileDialog.FileName);
                           this.ViewModel.PackageInfo= converterService.FromJsonString<PackageInfo>(text);
                        }  
                        break;
                    default:
                        break;
                }
            }

        }

        private void CommandBinding_CanExecute_1(object sender, CanExecuteRoutedEventArgs e)
        {
            if (ViewModel!=null&& ViewModel.PackageInfo!=null&&ViewModel.PackageInfo.Version!=null&&ViewModel.PackageInfo.PackageSize>0)
            {
                e.CanExecute = true;
            }
            else
            {
                e.CanExecute = false;
            }
        }

        private void CommandBinding_Executed_1(object sender, ExecutedRoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog=new SaveFileDialog();
            saveFileDialog.Filter = "打包后的固件包|*.pkgbin";
            saveFileDialog.FileName = $"{ViewModel.PackageInfo.Version.ToHex()}_{ViewModel.PackageInfo.PackageCount}_{ViewModel.PackageInfo.PackageSize}_{ViewModel.PackageInfo.PackageCheck}.pkgbin";
            if (saveFileDialog.ShowDialog()==true)
            {
                File.WriteAllText(saveFileDialog.FileName,converterService.ToJsonString(ViewModel.PackageInfo));
            }
        }

        private void CommandBinding_CanExecute_2(object sender, CanExecuteRoutedEventArgs e)
        {
            if (ViewModel != null && ViewModel.PackageInfo != null && ViewModel.PackageInfo.Version != null && ViewModel.PackageInfo.PackageSize > 0)
            {
                e.CanExecute = true;
            }
            else
            {
                e.CanExecute = false;
            }
        }

        private void CommandBinding_Executed_2(object sender, ExecutedRoutedEventArgs e)
        {
            options.Value.PackageInfo = this.ViewModel.PackageInfo;
            applicationBooster.UpdateAppSettingFile(options.Value);
        }
    }
}
